package com.nirvana.admin.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import com.nirvana.admin.config.CaptchaProperties;
import com.nirvana.admin.entity.vo.CaptchaResponseVO;
import com.nirvana.admin.service.CaptchaService;
import com.nirvana.common.util.RedisUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 验证码 Service 实现类
 *
 * @author zhangshuaiyin
 * @date 2021-09-29 10:35
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Resource
    private CaptchaProperties captchaProperties;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public CaptchaResponseVO getCaptchaImage() {
        // 生成验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());

        // 缓存到 Redis 中
        String uuid = IdUtil.fastSimpleUUID();
        redisUtils.set(uuid, captcha.getCode(), captchaProperties.getTimeout().toMillis());

        // 返回
        return CaptchaResponseVO.builder().uuid(uuid).img(captcha.getImageBase64()).build();
    }

    @Override
    public String getCaptchaCode(String uuid) {
        return (String) redisUtils.get(uuid);
    }

    @Override
    public void deleteCaptchaCode(String uuid) {
        redisUtils.del(uuid);
    }
}
